//
//  LKMySubordinateViewController.m
//  Mideleague_Agent
//
//  Created by Zhiwang on 2020/6/1.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKMySubordinateViewController.h"
#import "LKSearchBar.h"
#import "LKMyShopListCell.h"
#import "LKMySubordinateDetailViewController.h"
#import "LKMySuboraListModel.h"
#import "LKMySubordinateSearchResultViewController.h"
#import "LKDirectShopViewController.h"
@interface LKMySubordinateViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate>


@property(nonatomic,strong)LKSearchBar *mySearchBar;
@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,copy)NSString * timeType;
@property(nonatomic,copy)NSString * priceType;
@property(nonatomic,copy)NSString * levelType;
@property(nonatomic,strong)NSMutableArray *levelArray;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)NSMutableDictionary *paramDic;
@property(nonatomic,copy)NSString *currentSelectedKey;
@property(nonatomic,copy)NSString *currentSelectedValue;



@property (nonatomic,retain) UISearchController *searchController;
@property(nonatomic,strong)LKMySubordinateSearchResultViewController *searchResultVc;
@property(nonatomic,strong)UIView *searchBarView;
//@property(nonatomic,strong)NSMutableDictionary *paramDic;
@end

@implementation LKMySubordinateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"下级代理";
    self.page = 0;
//    self.priceType = @"1";
//    self.timeType = @"1";
//    self.levelType = @"0";
    self.priceType = @"";
    self.timeType = @"";
    self.levelType = @"";
    [self getMyAgentLevelInformationData];
    if (self.uid) {
        self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"id":self.uid,@"page":@(self.page),@"sort_type":self.priceType,@"is_search":@(NO)}];
    }else{
        self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.page),@"sort_type":self.priceType,@"is_search":@(NO)}];
    }

    self.currentSelectedKey = @"sort_type";
    self.currentSelectedValue = self.priceType;
    [self getMySubordinateListDataWithType:self.priceType AndWithKey:@"sort_type"];
//    [self getListStatus];
    // Do any additional setup after loading the view.
}
//设置搜索框
-(void)setupSearchView{

    self.searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, 40)];
    _searchBarView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_searchBarView];
    WMZDropMenuParam *param =
    MenuParam()
    .wMainRadiusSet(0)
    .wCollectionViewCellSelectTitleColorSet(yellowDefaultColor)
    .wCollectionViewSectionRecycleCountSet(3)
    .wMaxHeightScaleSet(0.6)
    .wBorderShowSet(NO)
    .wCellSelectShowCheckSet(NO)
    .wMenuTitleEqualCountSet(3);
    
    WMZDropDownMenu *menu = [[WMZDropDownMenu alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 40, WIDTH, 40) withParam:param];
    menu.delegate = self;
    [self.view addSubview:menu];
    self.tableView = [LKBaseTableview setTableviewWithFrame:CGRectZero style:UITableViewStyleGrouped registercellClasss:@[@"LKMyShopListCell"]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.emptyDataSetSource = self;
    _tableView.emptyDataSetDelegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(menu.mas_bottom).offset(1);
        make.bottom.equalTo(self.view).offset(0);
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
    [self.tableView reloadData];
}
/// 上拉刷新
-(void)headerReloadData{
    self.page = 0;
    [self.paramDic setObject:@(self.page) forKey:@"page"];
    [self getMySubordinateListDataWithType:self.currentSelectedValue AndWithKey:self.currentSelectedKey];
}

/// 下拉加载更多
-(void)footerReloadData{
    self.page++;
    [self.paramDic setObject:@(self.page) forKey:@"page"];
    [self getMySubordinateListDataWithType:self.currentSelectedValue AndWithKey:self.currentSelectedKey];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMyShopListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyShopListCell"];
    cell.listType = CellListTypeMySuboradinate;
    cell.mySuboralistModel = self.dataArray[indexPath.section];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 135.0f;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] init];
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.000000001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] init];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMySuboraListModel *model = self.dataArray[indexPath.section];
    LKMySubordinateDetailViewController *vc = [[LKMySubordinateDetailViewController alloc] init];
    vc.uid = model.uid;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self getMySubordinateListDataWithType:searchBar.text AndWithKey:@"word"];
    NSLog(@"SearchButton");
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.text = @"";
    self.priceType = @"1";
    [self getMySubordinateListDataWithType:self.priceType AndWithKey:@"sort_type"];
    UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"]; //首先取出cancelBtn
    cancelBtn.enabled = YES; //把enabled设置为yes
    [searchBar resignFirstResponder];
    
}
- (UIView *)findViewWithClassName:(NSString *)className inView:(UIView *)view{
    Class specificView = NSClassFromString(className);
    if ([view isKindOfClass:specificView]) {
        return view;
    }
    if (view.subviews.count > 0) {
        for (UIView *subView in view.subviews) {
            UIView *targetView = [self findViewWithClassName:className inView:subView];
            if (targetView != nil) {
                return targetView;
            }
        }
    }
    
    return nil;
}

#pragma mark -Menu的代理设置

- (NSArray*)titleArrInMenu:(WMZDropDownMenu *)menu{
    return @[
        @{@"name":@"全部代理",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"},
        @{@"name":@"全部日期",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"},
        @{@"name":@"金额高到低",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"}
    ];
}


- (NSInteger)menu:(WMZDropDownMenu *)menu numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSArray *)menu:(WMZDropDownMenu *)menu dataForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
      if (dropIndexPath.section == 0){
          return self.levelArray;
      }else if (dropIndexPath.section == 1){
          return @[@"全部时间",@"昨天",@"本周",@"本月"];
      }else if (dropIndexPath.section == 2){
          return @[@"交易额由高到低",@"交易额由低到高",@"开户时间最新",@"开户时间最久"];
      }
      return @[];
}


- (NSInteger)menu:(WMZDropDownMenu *)menu countForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return 2;
}
/*
*是否关联 其他标题 即选中其他标题 此标题会不会取消选中状态 default YES
*/
- (BOOL)menu:(WMZDropDownMenu *)menu dropIndexPathConnectInSection:(NSInteger)section{
    return NO;
}
- (CGFloat)menu:(WMZDropDownMenu *)menu heightAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath AtIndexPath:(NSIndexPath *)indexpath{
    if (dropIndexPath.section == 0 || dropIndexPath.section == 1 || dropIndexPath.section == 2) {
        return 50;
    }
    return 35;
}

- (MenuUIStyle)menu:(WMZDropDownMenu *)menu uiStyleForRowIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return MenuUITableView;
}

- (MenuHideAnimalStyle)menu:(WMZDropDownMenu *)menu hideAnimalStyleForRowInSection:(NSInteger)section{
    return MenuHideAnimalTop;
}

- (MenuShowAnimalStyle)menu:(WMZDropDownMenu *)menu showAnimalStyleForRowInSection:(NSInteger)section{
      return MenuShowAnimalBottom;
}


- (UITableViewCell*)menu:(WMZDropDownMenu *)menu cellForUITableView:(WMZDropTableView *)tableView AtIndexPath:(NSIndexPath *)indexpath dataForIndexPath:(WMZDropTree *)model{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GanJiTableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GanJiTableViewCell"];
    }
    cell.textLabel.text = model.name;
    cell.textLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13];
    cell.textLabel.textColor = model.isSelected?yellowDefaultColor:MenuColor(0x666666);
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;
}
- (BOOL)menu:(WMZDropDownMenu *)menu closeWithTapAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return YES;
}

-  (void)menu:(WMZDropDownMenu *)menu didSelectRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath dataIndexPath:(NSIndexPath *)indexpath data:(WMZDropTree *)data{
    if (dropIndexPath.section == 0) {
        self.page = 0;
         self.levelType = [NSString backSuboradinateTypeAccoringTitle:data.name];
        if (self.uid) {
            self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"id":self.uid,@"page":@(self.page),@"sort_type":self.priceType,@"time_type":self.timeType,@"level":self.levelType,@"is_search":@(NO)}];
        }else{
            self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.page),@"sort_type":self.priceType,@"time_type":self.timeType,@"level":self.levelType,@"is_search":@(NO)}];
        }
        if (self.levelType.length == 0) {
            [self.paramDic removeObjectForKey:@"level"];
        }
        [self getMySubordinateListDataWithType:self.levelType AndWithKey:@"level"];
        self.currentSelectedKey = @"level";
        self.currentSelectedValue = self.levelType;
    }
    if (dropIndexPath.section == 1) {
        self.page = 0;
        if (indexpath.row == 0) {
           self.timeType = [NSString stringWithFormat:@"%ld",(long)indexpath.row];
        }else{
           self.timeType = [NSString stringWithFormat:@"%ld",(long)indexpath.row + 1];
        }
        if (self.uid) {
            self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"id":self.uid,@"page":@(self.page),@"sort_type":self.priceType,@"time_type":self.timeType,@"level":self.levelType,@"is_search":@(NO)}];
        }else{
            self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.page),@"sort_type":self.priceType,@"time_type":self.timeType,@"level":self.levelType,@"is_search":@(NO)}];
        }
        if (self.levelType.length == 0) {
            [self.paramDic removeObjectForKey:@"level"];
        }
        [self getMySubordinateListDataWithType:self.timeType AndWithKey:@"time_type"];
        self.currentSelectedKey = @"time_type";
        self.currentSelectedValue = self.timeType;
    }
    if (dropIndexPath.section == 2) {
        self.page = 0;
        self.priceType = [NSString stringWithFormat:@"%ld",(long)indexpath.row + 1];
        if (self.uid) {
            self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"id":self.uid,@"page":@(self.page),@"sort_type":self.priceType,@"time_type":self.timeType,@"level":self.levelType,@"is_search":@(NO)}];
        }else{
            self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.page),@"sort_type":self.priceType,@"time_type":self.timeType,@"level":self.levelType,@"is_search":@(NO)}];
        }
        if (self.levelType.length == 0) {
            [self.paramDic removeObjectForKey:@"level"];
        }
        [self getMySubordinateListDataWithType:self.priceType AndWithKey:@"sort_type"];
        self.currentSelectedKey = @"sort_type";
        self.currentSelectedValue = self.priceType;
    }

}

//获取我的下级代理列表数据
-(void)getMySubordinateListDataWithType:(NSString *)type AndWithKey:(NSString *)key{
    //@"time_type":self.timeType
    NSMutableDictionary *param;
    if (self.uid) {
        
        
        
        if ([key isEqualToString:@"word"]) {
//            param = [[NSMutableDictionary alloc] initWithObjectsAndKeys:self.uid,@"id",type,key,@(YES),@"is_search", nil];
        }else{

//            param = [[NSMutableDictionary alloc] initWithObjectsAndKeys:self.uid,@"id",type,key,@(self.page),@"page", nil];
        }

    }else{

//        if ([key isEqualToString:@"word"]) {
//            param = [[NSMutableDictionary alloc] initWithObjectsAndKeys:type,key,@(YES),@"is_search", nil];
//        }else{
//            param = [[NSMutableDictionary alloc] initWithObjectsAndKeys:type,key,@(self.page),@"page", nil];
//        }

    }
    [SVProgressHUD show];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MySuboradinateListUrl header:[LKUserInforTool account].token parameters:self.paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"success"]) {
            [SVProgressHUD dismiss];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            if (self.page == 0) {
                [self.dataArray removeAllObjects];
            }
            NSArray *dataArray = responseObject[@"data"];
            if (dataArray.count < 15) {
                for (NSDictionary *dic in dataArray) {
                    LKMySuboraListModel *model = [LKMySuboraListModel modelWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
                self.tableView.mj_footer.hidden = YES;
            }else{
                for (NSDictionary *dic in dataArray) {
                    LKMySuboraListModel *model = [LKMySuboraListModel modelWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}

/// 获取代理层级
-(void)getMyAgentLevelInformationData{
    NSDictionary *param = @{@"token":[LKUserInforTool account].token};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodGET serverUrl:ServerlUrl apiPath:MySuboradinateLevelUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"success"]) {
            NSArray *dataArray = responseObject[@"data"];
            for (NSDictionary *dic in dataArray) {
                [self.levelArray addObject:dic[@"role_name"]];
            }
            [self setupSearchView];
            [self setUpSearchViewController];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
//获取下级代理-进件审核列表
-(void)getListStatus{
    NSDictionary *param = [NSDictionary dictionary];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MySuboradinateAddCheckListUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

-(NSMutableArray *)levelArray{
    if (_levelArray == nil) {
        _levelArray = [[NSMutableArray alloc] init];
    }
    return _levelArray;
}

/// 设置搜索控制器
-(void)setUpSearchViewController{
        //创建UISearchController
        self.searchResultVc = [[LKMySubordinateSearchResultViewController alloc] init];
        UINavigationController *navSearchVc = [[UINavigationController alloc] initWithRootViewController:self.searchResultVc];
        self.searchController = [[UISearchController alloc]initWithSearchResultsController:navSearchVc];
        //设置代理
        self.searchController.delegate= self;
        self.searchController.searchResultsUpdater = self.searchResultVc;
        //包着搜索框外层的颜色
        self.searchController.searchBar.barTintColor = viewDefualtColor;
        //提醒字眼
        self.searchController.searchBar.placeholder= @"请输入代理名称搜索";
        //设置UISearchController的显示属性，以下3个属性默认为YES
        //搜索时，背景变暗色
        self.searchController.dimsBackgroundDuringPresentation = YES;
        //搜索时，背景变模糊
        self.searchController.obscuresBackgroundDuringPresentation = YES;
        
        //点击搜索的时候,是否隐藏导航栏
        self.searchController.hidesNavigationBarDuringPresentation = YES;
    [self.searchController.searchBar sizeToFit];
        //位置
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 40.0);
    self.searchController.view.backgroundColor = [UIColor whiteColor];
    self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [self.searchBarView addSubview:self.searchController.searchBar];
        #warning 如果进入预编辑状态,searchBar消失(UISearchController套到TabBarController可能会出现这个情况),请添加下边这句话
    self.definesPresentationContext=YES;

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
